<template>
  <div class="loginview">
    <NavBarView />
    <div class="login">
      <h1>安全验证</h1>
      <div class="">
        <p>请输入{{ phone }}收到的短信验证码，以完成身份验证~~</p>
      </div>
      <div style="margin-top: 80px">
        <van-form>
          <!-- 验证码 -->
          <van-field
            v-model="code"
            type="tel"
            placeholder="请输入验证码"
            maxlength="6"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                @click="getCodes"
                :disabled="flag"
                >{{ sendCode }}</van-button
              >
            </template>
          </van-field>
        </van-form>
        <van-button type="primary" block style="margin-top: 80px" @click="next"
          >下一步</van-button
        >
      </div>
    </div>
  </div>
</template>
    
<script setup lang="ts">
import NavBarView from "./components/NavBarView.vue";

import { onMounted, ref } from "vue";
import { getCode, verifyCode } from "./services/phoneLogin";
import { timeinterval } from "./utils/debounce";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const phone = ref("");
const code = ref("");
const sendCode = ref("发送验证码");
const flag = ref(false);
const time = ref(0);
const route = useRoute();
const router = useRouter();

onMounted(() => {
  phone.value = route.query.phone as string;
});
const getCodes = async () => {
  try {
    let res: any = await getCode({ phone: phone.value });
    console.log(res);
    time.value = res.time;
    sendCode.value = "60秒后重新发送";
    flag.value = true;
    console.log(11111);
    timeinterval(59);
  } catch (error) {
    console.log(error);
  }
};

// 定时器
function timeinterval(time: number) {
  let timer = setInterval(() => {
    if (time > 0) {
      sendCode.value = `${time}秒后重新发送`;
      time--;
    } else {
      clearInterval(timer);
      sendCode.value = "发送验证码";
      flag.value = false;
    }
  }, 1000);
}

const next = async() => {
  let res: any =await verifyCode({ phone: phone.value, code: code.value });
  console.log(res.code);
  if (res.code == 200) {
    router.push('/newPsd?_id=' + res._id)
    console.log(res._id)
  } else {
    ElMessage.error(res.msg);
  }
};
</script>
    
<style scoped lang="scss">
.loginview {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  .login {
    width: 100%;
    height: 100%;
    background-size: 100% 100%;
    padding: 0% 20px;
    margin-top: 46px;
    box-sizing: border-box;
    .login-form {
      margin-top: 6ex;
      .van-field {
        margin-bottom: 20px;
      }
    }
    h1 {
      font-weight: 700;
      margin-bottom: 20px;
    }
    .agreement {
      margin-bottom: 20px;
      span {
        color: #1989fa;
      }
    }
    .other-login {
      margin-top: 60px;
    }
  }
}
</style>